
import socket
import struct
from threading import Thread
try:
        from scapy.all import *
except:
        try:
                from scapy import *
        except:
                print "Error. Scapy Not Found. apt-get install scapy python-scapy"

import time, signal, os
from NMUtils import *

MAX_TO_READ=65535

def handler(signum, frame):
	print 'SIGINT CAPTURED. Exiting...', signum
	time.sleep(2)
	exit(20)


class NMListener(Thread):

	def __init__(self, dst, dport, iface=None, crypt=None):
		self.dst=dst
		self.dport=dport
		self.iface=iface
		self.crypt=crypt	
		self.skt=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		#self.skt.connect((dst,dport))
		self.MIRROR_MAGIC=0xcabecafe
		signal.signal(signal.SIGINT, handler)

		try:
			self.skt.bind(('', dport))
		except socket.error, err:
			logger.error("Couldn't be a udp server on port %d : %s" % (dport, err))
			raise SystemExit
		Thread.__init__(self)
		logger.info("Listening on port " + str(dport))
		
	def run(self):
		while True:
			logger.info("RECEIVING Mirror magic: " + str(self.MIRROR_MAGIC))
			datagram=self.skt.recv(MAX_TO_READ)
			if not datagram:
				logger.error("NO DATAGRAM!!!!!")
				exit

			magic_rcv=0L
			buff=None

			(magic_rcv,buff)=struct.unpack("L%ds" % (len(datagram)-struct.calcsize("L")),datagram)
			if magic_rcv==self.MIRROR_MAGIC:
				p=Ether(buff)
				if p is not None:
					#logger.debug( "Received Packet!!!!!! : " + str(p.display()))
					if self.iface is not None:
						conf.verb=0
						sendp(p,iface=self.iface,verbose=0)
			else:
				logger.error("NO MAGIC HEADER!!!!!")


#Net Mirror (c) 2009 Pablo Rincon Crespo
